package cn.tedu.charging.order.mqtt;

import cn.tedu.charging.order.common.MqttConstants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * EMQX消息中间件的发送者
 */

@Slf4j
@Component
public class MqttProducer {

    @Autowired
    private MqttClient mqttClient;

    /**
     * 通过MqttConfiguration配置的mqttClient
     * @Bean注解创建的MqttClient 创建后,会放入到容器
     * 发送消息给EMQX
     * @param topic 主题
     * @param message 消息
     * @return
     */
    public Boolean publish(String topic, String message) {
        Boolean success = false;
        try {
            mqttClient.publish(topic,message.getBytes(),0,true);
            success = true;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
        return success;
    }
}
